package com.hisense.hiioc.hismartplate.controller;

import com.hisense.hiioc.hismartplate.constants.URLConstant;
import com.hisense.hiioc.hismartplate.entity.dto.MesRobot;
import com.hisense.hiioc.hismartplate.service.RobotService;
import com.hisense.hiioc.hismartplate.service.SpeechService;
import com.hisense.hiioc.hismartplate.web.response.MultipartResponse;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Auther:biexiande@hisense.com
 * @date:2018/12/17 9:35
 * @des
 */
@RestController
@RequestMapping(URLConstant.RobotURLMapping.BASE_URL)
public class RobotController {

    @Autowired
    RobotService robotService;
    @Autowired
    SpeechService speechService;


    @ApiOperation(value = "机器人对话问答接口")
    @ApiImplicitParam(name = "mesRobot", value = "机器人问答上行数据", required = true, dataType = "MesRobot")
    @PostMapping("/interact")
    public void interact(@RequestBody MesRobot mesRobot,HttpServletResponse response) throws IOException {
        //process in handlerchain
        List<String> directives =robotService.dialog(mesRobot);
        ServletOutputStream out = response.getOutputStream();
        MultipartResponse multi = new MultipartResponse(response);
        for (String directive : directives) {
            multi.startResponse("application/json; charset=utf-8");
            out.write(directive.getBytes("UTF-8"));
        }
        out.println();
        multi.finish();
    }
    @ApiOperation(value = "语音合成接口")
    @GetMapping("/speechsy")
    public ResponseEntity<byte[]> speechsy(@ApiParam(name="content",value="语音合成的文本") @RequestParam String content, HttpServletResponse response) {
        byte[] audioBytes =speechService.text2AudioService(content);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"","speech.mp3"));
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(audioBytes.length)
                .contentType(MediaType.parseMediaType("audio/mp3"))
                .body(audioBytes);
    }
}